package com.youlu.campus.admin.activity.controller;

import com.youlu.campus.admin.activity.service.ActivityRankingService;
import com.youlu.campus.admin.annotation.RequestActivityAuth;
import com.youlu.campus.admin.auth.entity.SystemRole;
import com.youlu.campus.admin.auth.entity.SystemUser;
import com.youlu.campus.admin.auth.service.RoleService;
import com.youlu.campus.admin.auth.service.UserService;
import com.youlu.campus.admin.community.dto.ActivityOnTopRequest;
import com.youlu.campus.admin.community.dto.ActivityQueryRequest;
import com.youlu.campus.admin.community.dto.ActivitySignQueryRequest;
import com.youlu.campus.admin.community.entity.ActivityTransferVo;
import com.youlu.campus.admin.community.service.ActivityService;
import com.youlu.campus.admin.utils.AuthUtils;
import com.youlu.campus.admin.utils.IpUtils;
import com.youlu.campus.common.base.RestResult;
import com.youlu.campus.common.base.RestResultBuilder;
import com.youlu.campus.entity.ActivityInfo;
import com.youlu.campus.entity.UserActivityFootPrint;
import com.youlu.campus.entity.UserParticipateActivityInfo;
import com.youlu.campus.entity.VO.req.ActivityFootPrintQueryVO;
import com.youlu.campus.entity.VO.req.ActivityOrgReq;
import com.youlu.campus.entity.VO.req.UserDataPermissionUpdateVO;
import com.youlu.campus.entity.VO.res.ActivityRankingPointsVO;
import com.youlu.campus.entity.system.UserDataPermission;
import com.youlu.campus.service.AdminExportUserSignUpService;
import com.youlu.campus.service.activity.ActivityFootPrintService;
import com.youlu.campus.service.activity.UserParticipateActivityInfoService;
import com.youlu.campus.service.ca.CaRecieveService;
import com.youlu.campus.service.platform.PlatformConfigService;
import com.youlu.campus.service.qa.UserQaInfoService;
import com.yuelin.infrastructure.quantum.common.QResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotNull;
import java.util.List;
import java.util.Map;

/**
 * 活动管理API
 *
 * @author: zhuhuaiqi
 * @date: 2020/12/11 17:18
 */
@Slf4j
@RestController
public class ActivityController {

    @Autowired
    private ActivityService activityService;
    @Autowired
    private com.youlu.campus.service.activity.ActivityService aService;
    @Autowired
    private CaRecieveService caRecieveService;
    @Autowired
    private PlatformConfigService platformConfigService;
    @Autowired
    private UserParticipateActivityInfoService userParticipateActivityInfoService;
    @Autowired
    private ActivityFootPrintService activityFootPrintService;

    @Autowired
    private AdminExportUserSignUpService adminExportUserSignUpService;

    @Autowired
    private RoleService roleService;

    @Autowired
    private UserService userService;

    @Autowired
    private ActivityRankingService activityRankingService;
    @Lazy
    @Autowired
    private UserQaInfoService userQaInfoService;

    /**
     * 创建活动
     *
     * @param request
     * @return
     */
    @PostMapping("/activity/create")
    public QResult createActivity(@RequestBody @NotNull ActivityInfo request) {
        request.setCreatorId(AuthUtils.getUserId());
        boolean result = activityService.createActivity(request);
        return QResult.success(result);
    }

    /**
     * 修改活动
     *
     * @param request
     * @return
     */
    @PostMapping("/activity/update")
    @RequestActivityAuth(activityId = "#request.id")
    public QResult updateActivity(@RequestBody ActivityInfo request) {
        boolean result = activityService.updateActivity(request);
        return QResult.success(result);
    }

    @PostMapping("/activity/config-org")
    @RequestActivityAuth(activityId = "#request.id")
    public QResult updateActivityOrg(@RequestBody ActivityOrgReq request) {
        activityService.updateActivityOrg(request);
        return QResult.success(null);
    }

    /**
     * 删除活动
     *
     * @param id
     * @return
     */
    @DeleteMapping("/activity/delete")
    @RequestActivityAuth(activityId = "#request.id")
    public QResult deleteActivity(String id) {
        if (StringUtils.isBlank(id)) {
            return QResult.fail("请求参数异常: id is null");
        }
        boolean result = activityService.deleteActivity(id);
        return QResult.success(result);
    }

    /**
     * 活动列表
     *
     * @param request
     * @return
     */
    @PostMapping("/activity/list")
    public QResult activityList(@RequestBody ActivityQueryRequest request) {
        request.setUserId(AuthUtils.getUserId());
        try {
            return QResult.success(activityService.activityList(request));
        } catch (Exception e) {
            log.error(":>>> 活动列表错误:{}", e);
            return QResult.fail("活动列表错误");
        }
    }

    /**
     * 活动置顶
     *
     * @param request
     * @return
     */
    @PostMapping("/activity/on/top")
    public QResult activityList(@Validated @RequestBody ActivityOnTopRequest request) {
        request.setUserId(AuthUtils.getUserId());
        try {
            return QResult.success(activityService.activityOnTop(request));
        } catch (Exception e) {
            log.error(":>>> 活动置顶:{}", e);
            return QResult.fail("活动置顶错误");
        }
    }

    /**
     * 活动信息查询
     *
     * @param id
     * @return
     */
    @GetMapping("/activity/query")
    public QResult query(String id) {
        return QResult.success(activityService.query(id));
    }

    /**
     * 活动报名用户列表
     *
     * @param request
     * @return
     */
    @PostMapping("/activity/sign/user/list")
    public QResult signUpList(@RequestBody ActivitySignQueryRequest request) {
        String userId = AuthUtils.getUserId();
        List<SystemRole> roleList = roleService.findAllByUserId(userId);
        long count = roleList.stream().filter(role -> role.getMobileDesensitization()).count();
        if (count > 0) {
            request.setMobileDesensitization(Boolean.TRUE);
            log.info("【手机号脱敏】当前用户 ->{} 手机号脱敏", AuthUtils.getLoginName());
        }
        long countMobileHide = roleList.stream().filter(role -> role.getMobileHide()).count();
        if (countMobileHide > 0) {
            log.info("【手机号隐藏】当前用户 ->{} 手机号隐藏", AuthUtils.getLoginName());
            request.setMobileHide(Boolean.TRUE);
        }
        return QResult.success(activityService.signUpList(request));
    }


    @PostMapping("/activity/rank/user/list")
    public QResult activityRankList(@RequestBody ActivityRankingPointsVO request) {
        return QResult.success(activityRankingService.findByPage(request));
    }

    /**
     * 初始化排行 用户数据
     *
     * @param activityId
     * @return
     */
    @GetMapping("/activity/rank/user/init")
    public QResult activityRankList(@RequestParam String activityId) {
        activityRankingService.initUserActivityRanking(activityId);
        return QResult.success(true);
    }

    @DeleteMapping("/activity/sign/user/delete/{id}")
    public QResult deleteUserSiginUp(@PathVariable String id) {
        SystemUser systemUser = userService.get(AuthUtils.getUserId());
        userParticipateActivityInfoService.deleteUserSignUp(id, systemUser.getMobile(), AuthUtils.getUserId());
        return QResult.success(null);
    }

    @PostMapping("/activity/sign/user/cancel")
    public QResult cancelUser(@RequestBody ActivitySignQueryRequest request) {

        return QResult.success(activityService.signUpList(request));
    }

    /**
     * 活动报名足迹修改
     *
     * @param request
     * @return
     */
    @PostMapping("/activity/print/update")
    public QResult updatePrint(@RequestBody UserActivityFootPrint request) {
        request.setUserId(AuthUtils.getUserId());
        return QResult.success(activityFootPrintService.updateUserActivityFootPrint(request));
    }

    /**
     * 批量修改活动报名足迹
     *
     * @param request
     * @return
     */
    @PostMapping("/activity/print/batch-update")
    public QResult batchUpdatePrint(@RequestBody UserActivityFootPrint request) {
        request.setUserId(AuthUtils.getUserId());
        return QResult.success(activityFootPrintService.batchUpdatePrint(request));
    }

    /**
     * 活动报名足迹列表
     *
     * @param req
     * @return
     */
    @PostMapping("/activity/print/list")
    public QResult listPrint(@RequestBody ActivityFootPrintQueryVO req) {
        return QResult.success(activityService.footPrintList(req));
    }

    /**
     * 活动报名足迹图片列表
     *
     * @param req
     * @return
     */
    @PostMapping("/activity/print/image/list")
    public QResult imageListPrint(@RequestBody ActivityFootPrintQueryVO req) {
        return QResult.success(activityService.imageListPrint(req));
    }

    /**
     * 所有用户导出
     *
     * @param
     * @param response
     */
    @PostMapping("/activity/sign-up/users/export")
    public RestResult orderUsers(HttpServletResponse response) {
        boolean result = aService.orderAllUsers(response);
        log.info(":>>> 导出所有用户结果:{}", result);
        if (result) {
            return RestResultBuilder.builder().success().build();
        }
        return RestResultBuilder.builder().failure().build();
    }

    /**
     * 领取证书生成
     *
     * @return
     */
    @PostMapping("/activity/ca-recieve/generate")
    @RequestActivityAuth(activityId = "#activityId")
    public QResult generateCaRecieve(@RequestParam("activityId") String activityId, @RequestParam(value = "limit", required = false) Boolean limit, HttpServletRequest response) {
        return QResult.success(caRecieveService.generateRecieveInfos(activityId, "", 1, limit, IpUtils.getIpAddr(response),
                AuthUtils.getUserId(), AuthUtils.getLoginName()));
    }

    /**
     * A
     * 领取证书生成
     *
     * @returnA
     */
    @PostMapping("/activity/ca-recieve/generate/user")
    public QResult generateOneUserCaRecieve(@RequestParam("activityId") String activityId, @RequestParam("appId") String appId,
                                            @RequestParam("mobile") String mobile,
                                            @RequestParam(value = "bizType", defaultValue = "1") Integer bizType, HttpServletRequest response) {
        return QResult.success(caRecieveService.generateRecieveInfos(activityId, appId, bizType, true, IpUtils.getIpAddr(response),
                AuthUtils.getUserId(), AuthUtils.getLoginName()));
    }

    /**
     * 领取证书导出
     *
     * @return
     */
    @PostMapping("/activity/ca-recieve/export")
    public QResult exportCaRecieve(@RequestParam("activityId") String activityId,
                                   @RequestParam("taskId") String taskId,
                                   HttpServletResponse response, HttpServletRequest request) {
        return QResult.success(caRecieveService.exportRecieveInfos(activityId, taskId, response));
    }

    /**
     * 报名信息导出
     *
     * @param
     */
    @PostMapping("/activity/users/export")
    @RequestActivityAuth(activityId = "#activityId")
    public RestResult signUpUserExport(@RequestParam("activityId") String activityId,
                                       @RequestParam(value = "key", required = false) String key,
                                       @RequestParam(value = "invitedNumStart", required = false) Integer invitedNumStart,
                                       @RequestParam(value = "invitedNumEnd", required = false) Integer invitedNumEnd) {
        adminExportUserSignUpService.exportUserV2(activityId, AuthUtils.getLoginName(), AuthUtils.getUserId(), key, invitedNumStart,
                invitedNumEnd);
        return RestResultBuilder.builder().success().build();
    }

    /**
     * 报名信息导出
     *
     * @param
     */
    @PostMapping("/activity/all-users/export")
    public RestResult allUserExport(@RequestParam(value = "activityId", required = false) String activityId, HttpServletResponse response) {
        String result = aService.exportAllUser(activityId, AuthUtils.getLoginName(), AuthUtils.getUserId(), response);
        log.info(":>>> 导出所有用户信息结果:{}", result);
        if (!StringUtils.isBlank(result)) {
            return RestResultBuilder.builder().success().build();
        }
        return RestResultBuilder.builder().failure().build();
    }

    /**
     * 承办单位用户信息
     *
     * @param
     */
    @PostMapping("/mini-app/activity/org-users/export")
    public RestResult exportOrgUser(@RequestParam("userId") String userId, @RequestParam("activityId") String activityId, HttpServletResponse response) {
        String result = aService.exportOrgUsers(userId, activityId, response);
        log.info(":>>> 承办单位用户信息结果:{}", result);
        if (!StringUtils.isBlank(result)) {
            return RestResultBuilder.builder().success().build();
        }
        return RestResultBuilder.builder().failure().build();
    }

    @PostMapping("/activity/sign/user/update")
    @RequestActivityAuth(activityId = "#request.activityId")
    public QResult signUpList(@RequestBody UserParticipateActivityInfo request) {

        return QResult.success(activityService.updateUserInfo(request));
    }

    @PostMapping("/activity/sign/user/black-list")
    public QResult blackList(@RequestBody UserParticipateActivityInfo request) {

        return QResult.success(activityService.blackList(request, AuthUtils.getLoginName()));
    }

    @GetMapping("/activity/sign/user/find-one")
    public QResult findOnesignUpUser(@RequestParam("id") String id) {

        return QResult.success(activityService.findOnesignUpUser(id));
    }

    /**
     * 生成短链接
     *
     * @param id
     * @return
     */
    @GetMapping("/activity/short-url/generate")
    public QResult generateShortUrl(@RequestParam("id") String id, @RequestParam(value = "urlType", required = false) String urlType) {
        return QResult.success(platformConfigService.getShortUrlDomain() + "/" + activityService.generateShortUrl(id, urlType));
    }

    @PostMapping("/activity/new/list")
    public QResult newActivityList(@RequestBody ActivityQueryRequest request) {
        request.setUserId(AuthUtils.getUserId());
        try {
            return QResult.success(activityService.newActivityList(request));
        } catch (Exception e) {
            log.error(":>>> 活动列表错误:{}", e);
            return QResult.fail("活动列表错误");
        }

    }

    @GetMapping("/activity/joined-user")
    public QResult setJoinedUser(@RequestParam(value = "id", required = false) String id) {
        try {
            activityService.setJoinedCount(id);
            return QResult.success("ok");
        } catch (Exception e) {
            log.error(":>>> 活动报名人数错误:{}", e);
            return QResult.fail("活动报名人数错误");
        }

    }

    @GetMapping("/activity/university-s")
    public QResult sUniversity(@RequestParam(value = "total", required = false) Long total) {
        try {
            userParticipateActivityInfoService.statisticsActivity(total);
            return QResult.success("ok");
        } catch (Exception e) {
            log.error(":>>> 统计大学人数错误:{}", e);
            return QResult.fail("统计大学人数错误");
        }

    }

    @PostMapping("/activity/permission/update")
    @RequestActivityAuth(activityId = "#request.activityId")
    public QResult createActivityPermissiob(@RequestBody @NotNull UserDataPermissionUpdateVO request) {
        boolean result = activityService.updateUserPermission(request);
        return QResult.success(result);
    }

    @GetMapping("/activity/permission/find-one")
    public QResult getActivityPermissiob(@RequestParam("id") String id) {
        UserDataPermission result = activityService.getUserPermission(id);
        return QResult.success(result);
    }

    /**
     * 导出证书生成
     *
     * @return
     */
    @PostMapping("/activity/ca-recieve/export-all")
    public QResult exportCaRecieve(@RequestParam("activityId") String activityId, @RequestParam(value = "fileTaskId", required = true) String fileTaskId, HttpServletResponse response) {
        return QResult.success(caRecieveService.exportRecieveInfos(activityId, fileTaskId, response));
    }

    /**
     * 转移活动创建者
     *
     * @return
     */
    @PostMapping("/activity/creator/transfer")
    public QResult transferCreator(@RequestBody ActivityTransferVo activityTransferVo) {
        return activityService.transferCreator(activityTransferVo.getActivityId(), activityTransferVo.getNewCreatorId());

    }

    /**
     * 批量导入答题记录
     *
     * @param
     * @return
     */
    @PostMapping("/sign/user/qa/import")
    public RestResult shipImport(@RequestParam("file") MultipartFile file,
                                 @RequestParam(value = "activityId", required = false) String activityId,
                                 @RequestParam(value = "qaInfoId", required = false) String qaInfoId) {
        try {
            String fileName = file.getOriginalFilename();
            log.info(":>>> 批量导入答题记录:{}", fileName);
            Map<String, Object> res = userQaInfoService.batchImportQaRecord(file.getBytes(), fileName, activityId, qaInfoId);
            return RestResultBuilder.builder().success(res).build();

        } catch (Exception e) {
            log.info(":>>> 导入答题记录错误:{}", e);
            return RestResultBuilder.builder().failure().build();
        }
    }

}
